import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { select, Store } from '@ngrx/store';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Subject } from 'rxjs';
import { map, takeUntil } from 'rxjs/internal/operators';
import { Lyric, Song } from 'src/app/services/data-types/common.types';
import { SongService } from 'src/app/services/song.service';
import { BaseLyricLine, WyLyric } from 'src/app/share/wy-ui/wy-player/wy-player-panel/wy-lyric';
import { AppStoreModule } from 'src/app/store';
import { BatchActionsService } from 'src/app/store/batch-actions.service';
import { getCurrentSong, getPlayer } from 'src/app/store/selectors/player.selector';

@Component({
  selector: 'app-song-info',
  templateUrl: './song-info.component.html',
  styleUrls: ['./song-info.component.less']
})
export class SongInfoComponent implements OnInit {

  song!: Song;
  lyric!: BaseLyricLine[];

  currentSong!: Song;
  currentIndex: number = -1;
  controlLyric = {
    isExpand: false,
    label: '展开',
    iconCls: 'down'
  }
  private destroy$ =  new Subject<void>();

  constructor(
    private route: ActivatedRoute,
    private store$: Store<AppStoreModule>,
    private batchActionServe: BatchActionsService,
    private songService: SongService,
    private nzMessageServe: NzMessageService,
  ) {
    this.route.data.pipe(map(res => res.songInfo)).subscribe(([song, lyric])=> {
      this.song = song;
      this.lyric = new WyLyric(lyric).lines;
      this.listenCurrent();
    })
  }
  private listenCurrent(){
    this.store$
    .pipe(select(getPlayer), select(getCurrentSong), takeUntil(this.destroy$))
    .subscribe(song => {
      this.currentSong = song
      // if(song){
      //   this.currentIndex = findIndex(this.sheetInfo.tracks, song);
      // }else{
      //   this.currentIndex = -1;
      // }
    })
  }

  ngOnInit(): void {
  }
  // 添加一首歌曲
  onAddSong(song: Song, isPlay = false) {
    if(!this.currentSong || this.currentSong.id !== song.id){
      this.songService.getSongList(song)
      .subscribe(list => {
        if(list.length){
          this.batchActionServe.insertSong(list[0], isPlay)
        }else {
          this.nzMessageServe.create('warning' , '无url!')
        }
      })
    }
  }

  toggleLyric(){
    this.controlLyric.isExpand = !this.controlLyric.isExpand
    if(this.controlLyric.isExpand){
      this.controlLyric.label = '收起';
      this.controlLyric.iconCls = 'up';

    }else{
      this.controlLyric.label = '展开';
      this.controlLyric.iconCls = 'down';
    }
  }
}
